package net.flintx.array;

/**
 * Created by flintx on 2018/1/13.
 */
public class ImageSmoother {
    public int[][] imageSmoother(int[][] M) {
        int m = M.length, n = M[0].length;
        int[][] M2 = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                double sum = M[i][j];
                sum += (i > 0)? M[i - 1][j] : 0;
                sum += (j > 0)? M[i][j - 1] : 0;
                sum += (i < m - 1)? M[i + 1][j] : 0;
                sum += (j < n - 1)? M[i][j + 1] : 0;
                sum += (i > 0 && j > 0)? M[i - 1][j - 1] : 0;
                sum += (i > 0 && j < n - 1)? M[i - 1][j + 1] : 0;
                sum += (i < m - 1 && j > 0)? M[i + 1][j - 1] : 0;
                sum += (i < m - 1 && j < n - 1)? M[i + 1][j + 1] : 0;
                double count = 1;
                count += (i > 0)? 1 : 0;
                count += (j > 0)? 1 : 0;
                count += (i < m - 1)? 1 : 0;
                count += (j < n - 1)? 1 : 0;
                count += (i > 0 && j > 0)? 1 : 0;
                count += (i > 0 && j < n - 1)? 1 : 0;
                count += (i < m - 1 && j > 0)? 1 : 0;
                count += (i < m - 1 && j < n - 1)? 1 : 0;
                M2[i][j] = (int) Math.floor(sum / count);
            }
        }
        return M2;
    }
}
